package guzb.cnblogs.security.industrydemo.auth;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 自定义的用户明细实现类
 */
public class MyUserDetails implements UserDetails {

    private UserEntity userEntity;

    private List<? extends GrantedAuthority> grantedAuthorities;

    public MyUserDetails(UserEntity userEntity, List<? extends GrantedAuthority> grantedAuthorities) {
        this.userEntity = userEntity;
        this.grantedAuthorities = grantedAuthorities == null ? Collections.EMPTY_LIST : grantedAuthorities;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.grantedAuthorities;
    }

    @Override
    public String getPassword() {
        return userEntity.getPassword();
    }

    @Override
    public String getUsername() {
        return userEntity.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        if (userEntity.getAccountExpiryTime() == null) {
            return true;
        }
        return System.currentTimeMillis() - userEntity.getAccountExpiryTime().getTime() <= 0;
    }

    @Override
    public boolean isAccountNonLocked() {
        return Boolean.FALSE.equals(userEntity.getIsLocked());
    }

    @Override
    public boolean isCredentialsNonExpired() {
        Date lastPasswordUpdateTime = userEntity.getPasswordLastUpdateTime();
        if (lastPasswordUpdateTime == null) {
            return true;
        }
        // 密码有效期3个月
        return System.currentTimeMillis() - lastPasswordUpdateTime.getTime() <= 3 * 30 * 24 * 3600 * 1000;
    }

    @Override
    public boolean isEnabled() {
        return Boolean.TRUE.equals(userEntity.getIsEnabled());
    }

    public UserEntity getUserEntity() {
        return userEntity;
    }
}
